package com.myzl.stream.util.ffmpeg;

import com.myzl.common.constant.CacheConstants;
import com.myzl.common.core.redis.RedisCache;
import com.myzl.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author cew
 * @date 2023年7月20日17:26:29
 */
@Slf4j(topic = "admin-steam")
public class FfmpegUtil {

    public static ConcurrentHashMap<String, Process> processMap = new ConcurrentHashMap<>();
    private final static Integer LIVE_TIME = 15;


    public static Process getProcess(String videoUrl){
        String cacheKey = getCacheKey(videoUrl);
        return processMap.get(cacheKey);
    }

    public static String getPlayUrl(String videoUrl){
        String cacheKey = getCacheKey(videoUrl);
        return SpringUtils.getBean(RedisCache.class).getCacheObject(cacheKey);
    }

    public static boolean push(String videoUrl, String flvUrl, Process process){
        synchronized (FfmpegUtil.class){
            String cacheKey = getCacheKey(videoUrl);
            processMap.put(cacheKey,process);
            SpringUtils.getBean(RedisCache.class).setCacheObject(cacheKey,flvUrl, LIVE_TIME, TimeUnit.MINUTES);
            return true;
        }
    }

    public static boolean keepLive(String videoUrl){
        synchronized (FfmpegUtil.class){
            String cacheKey = getCacheKey(videoUrl);
            String cacheVideoUrl = SpringUtils.getBean(RedisCache.class).getCacheObject(cacheKey);
            if (ObjectUtils.isEmpty(cacheVideoUrl)){
                log.info("视频流保活失败：{}",videoUrl);
                return false;
            }
            SpringUtils.getBean(RedisCache.class).setCacheObject(cacheKey,cacheVideoUrl,LIVE_TIME,TimeUnit.MINUTES);
            log.info("视频流保活成功：{}",videoUrl);
            return true;
        }
    }

    public static boolean exists(String videoUrl){
        String cacheKey = getCacheKey(videoUrl);
        return SpringUtils.getBean(RedisCache.class).hasKey(cacheKey);
    }

    public static boolean destroy(String videoUrl){
        synchronized (FfmpegUtil.class){
            String cacheKey = getCacheKey(videoUrl);
            Process process = processMap.get(cacheKey);
            if (process != null){
                process.destroy();
                processMap.remove(cacheKey);
                log.info("视频url：{}",videoUrl);
                log.info("------------------------推流结束-------------------------");
            }
            SpringUtils.getBean(RedisCache.class).deleteObject(cacheKey);
            return true;
        }
    }

    private static String getCacheKey(String videoUrl)
    {
        return CacheConstants.CAMERA_KEY + videoUrl;
    }
}
